var NowPlaying = new Class.create({
	
	setOptions: function(options) {
		// Default options
		this.options = {
			defaultMsg: '',
			imageDir: 'images/',
			defaultRetry:30000,
			updateURL: null,
			onUpdateInit: Class.empty,
			onUpdate: Class.empty
		};
		Object.extend(this.options, options || {});
	},  
	initialize: function(box,options) {
		
		this.box = $(box);
		this.setOptions(options);
		
		this.messageID = -1;
		this.currentRating = 0;
		this.currentArtist = "";
		this.currentSong = "";
		this.currentMessage = "";
		this.responseType = false;
		this.updateTimer = this.updateSong.periodical(120000);
		this.myFader = this.box.effect('opacity', {duration:800,wait:true});
		
	},
	
	updateSong: function(params) {
		this.options.onUpdateInit();
		var songReq = new ajax(this.options.updateURL+'?'+params,{method:'POST', onComplete: this.onUpdateComplete.bind(this)});
		songReq.request();
	},
	
	onUpdateComplete: function(request) {

		this.updateTimer = $clear(this.updateTimer);
		this.box.innerHTML = this.options.defaultMsg;
		this.messageID = -1;
		
		try {
			var ResultSet = Json.evaluate(request);
			var iTimeLeft = ResultSet["TimeLeft"];
			if(iTimeLeft < 3) iTimeLeft = this.options.defaultRetry;
			this.responseType = ResultSet["Type"];
			this.currentArtist = ResultSet["Artist"] || "";
			this.currentSong = ResultSet["Song"] || "";
			this.currentMessage = ResultSet["message"] || "";
			this.currentRating = ResultSet["voteTotal"] || 0;
			this.messageID = ResultSet["ID"];
			this.updateTimer = this.updateSong.periodical(iTimeLeft*1000);
		}
		catch(e) {
			this.updateTimer = this.updateSong.periodical(this.options.defaultRetry);
			this.messageID = -1;
			this.box.innerHTML = this.options.defaultMsg;
			return;
		}
		
		this.startEffect();
		this.options.onUpdate();
	},
	
	startEffect: function() {
		this.myFader.options.onComplete = this.endEffect.bind(this);
		this.myFader.custom(1,0);
	},
	
	endEffect: function() {
		this.myFader.options.onComplete = function() { };
		this.setMessage();
		this.myFader.custom(0,1);
	},
	
	setMessage: function() {
		
		switch (this.responseType) { 
			case "song":
				this.box.innerHTML = this.currentSong + " <br /> " + this.currentArtist;
				break;
			case "message":
				this.box.innerHTML = "<strong>"+this.currentMessage+"/<strong>";
				break;
			case "userrate":
				this.box.innerHTML = this.currentSong + " <br /> " + this.currentArtist;
		} 
	}
	
});